import { createI18n } from 'vue-i18n';
import { Locale } from 'vant'
import enUS from 'vant/es/locale/lang/en-US'
import zhCN from 'vant/es/locale/lang/zh-CN'
import messages from './locale';
import { getQueryString } from '@/utils';

/** 默认语言包名称 */
const DEFAULT_LANGUAGE = 'zh-CN';

function getI18nLocale() {
  const chosenLanguage = getQueryString('lang') || localStorage.getItem('lang') || navigator.language;
  const locales = Object.keys(messages);
  for (const lang of locales) {
    if (lang === chosenLanguage) {
      return chosenLanguage; // 存在当前语言的语言包
    } else if (lang.indexOf(chosenLanguage) === 0) {
      return lang; // 存在当前语言的任意地区的语言包
    }
  }
  return DEFAULT_LANGUAGE; // 使用默认语言包
}

export const i18n = createI18n({
  locale: getI18nLocale(),
  fallbackLocale: DEFAULT_LANGUAGE,
  messages,
  legacy: false
});

// 载入 vant 语言包
Locale.use('zh-CN', zhCN);
Locale.use('en-US', enUS);

export const $t = i18n.global.t as any;

export function setLocale(locale?: App.I18n.LangType) {
  const local = locale || getI18nLocale();
  i18n.global.locale.value = local as App.I18n.LangType;
  localStorage.setItem('lang', local);
  Locale.use(local);
}
